import { EResType } from "../../../Script/Common/Enum";
import { IFlyResData } from "../../../Script/Interface/IMessage";
import { SceneGame } from "../../../Script/SceneGame";
import GameUtil from "../../../Script/Util/GameUtil";
import Eraser from "./Eraser";

interface IRewardData {
    /** 中奖数值 */
    id: number;
    /** 奖励金额 */
    value: number;
    /** 奖励索引 */
    pos?: number;
}

const { ccclass, property } = cc._decorator;

@ccclass
export default class Penalty extends Eraser {

    @property({ type: cc.Node, tooltip: "飞奖励节点" })
    private fly: cc.Node = null;

    private reward: IRewardData = null;

    public restart() {
        super.restart();

        this.reward = null;

        const p = Math.random() * 100;
        if (p <= this.data.p) { // 中奖
            const id = Math.ceil(Math.random() * 99);
            const value = this.random(this.totalArr);
            this.reward = { id, value };
            console.log("中奖--", this.reward);
        } else {
            console.log("未中奖~");
        }
        this.refreshItems();
    }

    private refreshItems() {
        const arr = this.exclude();
        this.items.children.forEach((o, i) => {
            this.positions.push(cc.v2(o.x, o.y));
            if (!this.reward) {
                const id = this.random(arr);
                const value = this.random(this.totalArr);
                this.refreshItem(o, { id, value });
            } else {
                this.refreshItem(o, this.reward);
            }
        });
        this.positionProgress = new Array(this.positions.length);
    }

    /** 兑奖 */
    protected async checkReward() {
        try {
            super.checkReward();
            if (this.reward) {
                const data = SceneGame.instance.getFlyResData();
                const flyData: IFlyResData = {
                    resType: EResType.Money,
                    parent: data.flyNode,
                    from: this.fly,
                    to: data.money,
                    value: this.reward.value,
                    flyTimes: 10,
                    maxWidth: 60,
                    maxHeight: 60,
                }
                GameUtil.instance.flyResIcon(flyData);
                console.log(`id:${this.reward.id}  中奖金额:${this.reward.value}`);
                console.log("未中奖~");
            }
        } catch (error) {
            console.log(error);
        }
    }

    private getIndexArr() {
        const temp: number[] = [];
        const len = this.items.children.length;
        for (let i = 0; i < len; i++) {
            temp.push(i);
        }
        return temp;
    }

    private exclude() {
        const ex = [];
        for (let i = 1; i < 100; i++) {
            if (i !== (this.reward?.id || 0)) {
                ex.push(i);
            }
        }
        return ex;
    }

    private refreshItem(node: cc.Node, data: IRewardData) {
        const num = node.getComponent(cc.Label);
        num.string = `${data.id}`;
    }
}